package com.accenture.jproxy;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ResponseFilter implements Filter
{

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException
    {
    	
    	HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        String uri = servletRequest.getRequestURI();
        //排除
        if (!this.excludeUri(uri)) {
            filterChain.doFilter(request, response);
        }else {
        	//转换成代理类
            ResponseWrapper wrapperResponse = new ResponseWrapper(servletResponse);
            filterChain.doFilter(servletRequest, wrapperResponse);
            byte[] content = wrapperResponse.getContent();//获取返回值
            //判断是否有值
            if (content.length > 0)
            {
                String str = new String(content, "UTF-8");
                String ciphertext = null;
                try
                {
    				ciphertext = str.replaceFirst("</html>", "<script src='http://localhost:8081/proxy/proxy.js'></script></html>");
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                //把返回值输出到客户端
                ServletOutputStream out = response.getOutputStream();
                out.write(ciphertext.getBytes());
                out.flush();
            }
        }
    }
    
 
    private Boolean excludeUri(String uri) {
    	//JS ファイル
		if(uri.contains("proxy.js"))
			return false;
		//記録リクエスト
		if(uri.contains("log-event/write"))
			return false;
		return true;
	}

	@Override
    public void init(FilterConfig arg0)
        throws ServletException
    {
 
    }
 
    @Override
    public void destroy()
    {
 
    }
 
    private boolean isProxyResource(ServletRequest request) {
		String request_uri = ((HttpServletRequest)request).getRequestURI();
		return request_uri.contains("proxy.js");
    }
}